<?php require_once('assets/tool/01_function.php'); ?>

<?php

class SiteController extends AdminController
{
    /**
     * Declares class-based actions.
     */
    public function actions()
    {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,
            ),
            // page action renders "static" pages stored under 'protected/views/site/pages'
            // They can be accessed via: index.php?r=site/page&view=FileName
            'page'=>array(
                'class'=>'CViewAction',
            ),
        );
    }


    /** actionIndex =========================
     * @author   TuanNguyen
     * @desc     show index view of site controller
     *
     * @param
     * @return
     * ============================================== */
    public function actionIndex()
    {
        //Init
        $s_errorMessage = null;
        $o_model = Website::getDataByID(1);
        if( ErrorEntity::isErrorEntity($o_model) )
        {
            $s_errorMessage = self::getErrorMessage($o_model);
        }

        // renders the view file 'protected/views/site/index.php'
        // using the default layout 'protected/views/layouts/main.php'
        $this->render('index', array("o_model" => $o_model));
    }//End actionIndex

    /**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        if($error=Yii::app()->errorHandler->error)
        {
            if(Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

    /**
     * Displays the contact page
     */
    public function actionContact()
    {
        $model=new ContactForm;
        if(isset($_POST['ContactForm']))
        {
            $model->attributes=$_POST['ContactForm'];
            if($model->validate())
            {
                $headers="From: {$model->email}\r\nReply-To: {$model->email}";
                mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
                Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
                $this->refresh();
            }
        }
        $this->render('contact',array('model'=>$model));
    }

    /**
     * Displays the login page
     */
    public function actionLogin()
    {
        if(isset($_REQUEST["txt_account"]))
        {
            $s_userName = $_REQUEST["txt_account"];
            $s_password = hash("sha512", $_REQUEST["txt_password"]);

            $account = new UserIdentity($s_userName,$s_password);
            $account->authenticate();

            if($account->errorCode !== UserIdentity::ERROR_NONE)
            {
                $this->render('login');
            }
            else
            {
                $duration = (isset($_REQUEST["remember_me"]) ? 3600*24*30 : 0); // 30 days
                Yii::app()->user->login($account,$duration);
                $this->redirect(Yii::app()->createUrl("site/index"));
            }
        } else
        {
            $this->render('login');
        }
    }

    /** actionLogout =========================
     * @author   TuanNguyen
     * @desc     remove all of current session of user
     *
     * @param
     * @return
     * ============================================== */
    public function actionLogout()
    {
        Yii::app()->user->logout();
    }//end actionLogout


    /** actionUploadImage =========================
     * @author   TuanNguyen
     * @desc     Upload Image to server
     *
     * @param
     * @return
     * ============================================== */
    public function actionUploadImage()
    {
        $o_error = new ErrorEntity();
        
        if( isset($_REQUEST["fileInputName"]) == false ||
            isset($_REQUEST["url_image"])     == false )
        {
            $o_error->errCode   = "ERR_3";
            $o_error->param     = null;
            $s_errorMessage     = self::getErrorMessage($o_error);
            exit(json_encode(array("error" => $s_errorMessage)));
        }

        $o_fileInputName     = $_REQUEST["fileInputName"];
        $s_destinationFolder = $_REQUEST["url_image"];
        $i_height            = null;
        $s_imageName         = null;

        if ( $o_fileInputName == "e_logo" )
        {
            $s_imageName = "website_logo";
            $i_height    = 136;
        }
        elseif ( $o_fileInputName == "e_logoFooter" )
        {
            $s_imageName = "website_logo_footer";
            $i_height    = 136;
        }
        elseif ( $o_fileInputName == "e_banner" )
        {
            $s_imageName = "website_banner";
            $i_height    = 136;
        }
        else
        {
            $o_error             = new ErrorEntity();
            $o_error->errCode    = "ERR_3";
            $o_error->param      = array("fieldName"=>"image banner");
            $s_errorMessage      = self::getErrorMessage($o_error);
            exit(json_encode(array("error" => $s_errorMessage)));
        }

        // Validate the file type
        $arr_types = array('jpg','jpeg','gif','png');

        $arr_result =  uploadImageAjax($arr_types, $o_fileInputName, $s_destinationFolder, null, $i_height, $s_imageName);

        if( is_array($arr_result) == true)
        {
            exit(json_encode($arr_result));
        }
        else
        {
            $arr_result = array("result" => $arr_result);
            exit(json_encode($arr_result));
        }
        Yii::app()->end();
    }//End actionUploadImage


    /** actionSave =========================
     * @author   TuanNguyen
     * @desc     Save information of website
     * 
     * @param
     * @return
     * ============================================== */
    public function actionSave()
    {
        //Init
        $s_errorMessage = null;
        
        $o_result = self::checkSaveParamRequest();
        if( ErrorEntity::isErrorEntity($o_result) )
        {
            $s_errorMessage = self::getErrorMessage($o_result);
            $s_requestParam = $s_errorMessage."||".Yii::app()->createUrl("site/index");
            throw new CHttpException(500,$s_requestParam);
        }

        $i_key              = $_REQUEST["item_key"];
        $s_shopName         = $_REQUEST["txt_shopName"];
        $s_urlLogo          = $_REQUEST["hid_logo"];
        $s_urlBanner        = $_REQUEST["hid_banner"];
        $s_urlLogoFooter    = $_REQUEST["hid_logoFooter"];
        $s_slogan           = $_REQUEST["txt_slogan"];
        $s_companyName      = $_REQUEST["txt_companyName"];
        $s_taxID            = $_REQUEST["txt_taxId"];
        $s_businessRegiCert = $_REQUEST["txt_businessRegiCert"];

        $o_website = new Website();
        $o_website->unsetAttributes();
        $o_website->key               = $i_key;
        $o_website->shop_name         = $s_shopName;
        $o_website->logo              = $s_urlLogo;
        $o_website->logo_footer       = $s_urlLogoFooter;
        $o_website->banner            = $s_urlBanner;
        $o_website->slogan            = $s_slogan;
        $o_website->company_name      = $s_companyName;
        $o_website->tax_id            = $s_taxID;
        $o_website->business_regiCert = $s_businessRegiCert;

        if ( $i_key == 0 )
        {
            $b_result = Website::addDataToDb($o_website);
            if( ErrorEntity::isErrorEntity($b_result) )
            {
                $s_errorMessage = self::getErrorMessage($b_result);
            }
        }
        elseif ( $i_key != 0 )
        {
            $b_result = Website::updateDataToDb($o_website);
            if( ErrorEntity::isErrorEntity($b_result) )
            {
                $s_errorMessage = self::getErrorMessage($b_result);
            }
        }

        if ($s_errorMessage != "")
        {
            $s_requestParam = $s_errorMessage."||".Yii::app()->createUrl("site/index");
            throw new CHttpException(500,$s_requestParam);
        }

        $this->redirect(Yii::app()->createUrl("site/index"));
    }//End actionSave


    /** checkSaveParamRequest =========================
     * @author   TuanNguyen
     * @desc     Check request param when user press btn_saveImage
     *           set reference parameter if there are an error
     * @param
     * @return   null or ErrorEntity
     * ============================================== */
    private function checkSaveParamRequest()
    {
        $o_error = new ErrorEntity();

        if( isset($_REQUEST["item_key"])         == false ||
        isset($_REQUEST["txt_shopName"])         == false ||
        isset($_REQUEST["hid_logo"])             == false ||
        isset($_REQUEST["hid_banner"])           == false ||
        isset($_REQUEST["hid_logoFooter"])       == false ||
        isset($_REQUEST["txt_slogan"])           == false ||
        isset($_REQUEST["txt_companyName"])      == false ||
        isset($_REQUEST["txt_taxId"])            == false ||
        isset($_REQUEST["txt_businessRegiCert"]) == false )
        {
            $o_error->errCode   = "ERR_3";
            $o_error->param     = null;
            return $o_error;
        }

        if ( is_numeric($_REQUEST["item_key"]) == false)
        {
            $o_error->errCode   = "ERR_4";
            $o_error->param     = array("fieldName"=>"item key", "formatName"=>"interger");
            return $o_error;
        }

        if( $_REQUEST["hid_logo"] == "" )
        {
            $o_error             = new ErrorEntity();
            $o_error->errCode    = "ERR_5";
            $o_error->param      = array("fieldName"=>"image logo");
            $s_errorMessage      = self::getErrorMessage($o_error);
            exit($s_errorMessage);
        }

        if( $_REQUEST["hid_banner"] == "" )
        {
            $o_error             = new ErrorEntity();
            $o_error->errCode    = "ERR_5";
            $o_error->param      = array("fieldName"=>"image banner");
            $s_errorMessage      = self::getErrorMessage($o_error);
            exit($s_errorMessage);
        }

        return null;
    }//End checkSaveParamRequest


    /** getErrorMessage =============================
     * @author   TuanNguyen
     * @desc     get error message from array of error entity
     *           set reference parameter if there are an error
     * @param    $errorEnts: array of error entity or error entity
     * @return   string: error message
     * ============================================== */
    private function getErrorMessage($errorEnts)
    {
        $arr_errorMessage    = array(
                "ERR_1" => "There are an error with parameters in SQL statement. ",
                "ERR_2" => "SQLException",
                "ERR_3" => "Recieved Parameter is wrong or missing. ",
                "ERR_4" => "format of fieldName is formatName, please type value as formatName format . ",
                "ERR_5" => "fieldName is empty, please set value for it. ",
                "ERR_6" => "ImageType don't exist in image configuration. ",
                "ERR_7" => "string length of fieldName is over stringLength. ",
        );
    
        //Return error message
        if ( is_array($errorEnts) )
        {
            return ErrorEntity::setErrorMessageByArray($errorEnts, $arr_errorMessage);
        }
        elseif ( $errorEnts instanceof ErrorEntity )
        {
            return ErrorEntity::setErrorMessageByEntity($errorEnts, $arr_errorMessage);
        }
    }//End getErrorMessage
}